﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;

namespace BTVPodcatcherNamespace
{
    public partial class MainForm : Form
    {
        private string _BTVServer = "127.0.0.1";
        private string _BTVPort = "8129";
        private string _BTVUsername = "";
        private string _BTVPassword = "";
        private int _updateTimerAmount = 60;
        private int _writeMediaAfter = 60;
        private bool _useTEMPFiles = true;
        private int _maximumWriteAmount = 500;
        private bool _showWhenMinimized = false;
        private int _throttleAmount = 0;
        private TimeSpan _startTimeSpan = new TimeSpan(0);
        private TimeSpan _stopTimeSpan = new TimeSpan(0);
        private List<RSSLibrary3.RSSFeed> _rssFeeds = new List<RSSLibrary3.RSSFeed>();
        private List<DowloadInfo> _allDownloadItems = new List<DowloadInfo>();
        private DownloadManager _downloadManager = new DownloadManager();
        private Queue<DowloadInfo> _toDownload = new Queue<DowloadInfo>();
        
        private bool _useSSL = false;
        private bool _readOnly = false;
        private bool _useUnsafeHTMLHeaderParsing = false;

        public int throtlleAmount
        {
            get { return _throttleAmount; }
        }
        public TimeSpan startTime
        {
            get { return _startTimeSpan; }
        }
        public TimeSpan stopTime
        {
            get { return _stopTimeSpan; }
        }
        public bool useSSL
        {
            get { return _useSSL; }
        }
        public bool setFilesToReadOnly
        {
            get {return _readOnly;}
        }
        public bool useUnsafeHTMLHeaderParsing
        {
            get {return _useUnsafeHTMLHeaderParsing;}
        }
        public static bool SetAllowUnsafeHeaderParsing20()
        {
            //Get the assembly that contains the internal class
            Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
            if (aNetAssembly != null)
            {
                //Use the assembly in order to get the internal type for the internal class
                Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
                if (aSettingsType != null)
                {
                    //Use the internal static property to get an instance of the internal settings class.
                    //If the static instance isn't created allready the property will create it for us.
                    object anInstance = aSettingsType.InvokeMember("Section",
                      BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });

                    if (anInstance != null)
                    {
                        //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
                        FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (aUseUnsafeHeaderParsing != null)
                        {
                            aUseUnsafeHeaderParsing.SetValue(anInstance, true);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
         public static bool SetDenyUnsafeHeaderParsing20()
        {
            //Get the assembly that contains the internal class
            Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
            if (aNetAssembly != null)
            {
                //Use the assembly in order to get the internal type for the internal class
                Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
                if (aSettingsType != null)
                {
                    //Use the internal static property to get an instance of the internal settings class.
                    //If the static instance isn't created allready the property will create it for us.
                    object anInstance = aSettingsType.InvokeMember("Section",
                      BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });

                    if (anInstance != null)
                    {
                        //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
                        FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (aUseUnsafeHeaderParsing != null)
                        {
                            aUseUnsafeHeaderParsing.SetValue(anInstance, false);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        public MainForm()
        {
            
            InitializeComponent();
            loadSettingsFiles();
            readBTVFeedFile();
            if ((_startTimeSpan == _stopTimeSpan) || (_startTimeSpan < _stopTimeSpan && DateTime.Now.TimeOfDay > _startTimeSpan && DateTime.Now.TimeOfDay < _stopTimeSpan) || (_stopTimeSpan < _startTimeSpan && (DateTime.Now.TimeOfDay < _stopTimeSpan || DateTime.Now.TimeOfDay > _startTimeSpan)))
            {
                updateAllFeeds();
            }
            _downloadManager.downloadFinished += new DownloadManager.DownloadFinishedDelegate(_downloadManager_downloadFinished);
            ConsoleForm.addMessage("Program Loaded");
            
        }

        void _downloadManager_downloadFinished(object sender, downloadFinishedEventArgs e)
        {
            ConsoleForm.addMessage("Download Finished");
            if (_toDownload.Count > 0)
            {
                ConsoleForm.addMessage("Start Download From Queue");
                DowloadInfo di = _toDownload.Dequeue();
                _downloadManager.StartDownload(di, _throttleAmount);
            }
            else
            {
                setNotifyIcon(0);
            }
            //TODO: ADD Cross Threading Call
            setDownloadStatusLabel( "Downloading " + (DownloadManager.numberRunning + _toDownload.Count) + " Items");
            
            if (e.downloadedItem.DownloadStatus== DownloadStatus.Complete && e.downloadedItem.RSSItem.rssFeed.btvIntergration)
            {
                e.downloadedItem.DownloadStatus = DownloadStatus.WaitingToWriteProperties;
                e.downloadedItem.ADownloadChangedOccured(new EventArgs());
                BTVWriter btw= new BTVWriter(e.downloadedItem, this);

                Thread btvWriter = new Thread(new ThreadStart(btw.writeBTVProprties));
                btvWriter.Name = "BTV Podcatcher Media Tag Writer";
                btvWriter.IsBackground = true;
                btvWriter.Start();
                
            }
        }
        private delegate void setDownloadStatusLabelDelegate(string text);
        private void setDownloadStatusLabel(string text)
        {
            if (toolStrip1.InvokeRequired)
            {
                toolStrip1.Invoke(new setDownloadStatusLabelDelegate(setDownloadStatusLabel), new object[] { text });
            }
            else
            {
                toolStripStatusLabel2.Text = text;
            }

        }
        private delegate void setNotifyIconDelegate(int i);
        private void setNotifyIcon(int i)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new setNotifyIconDelegate(setNotifyIcon), new object[] { i });
            }
            else
            {

                if ( i == 0)
                {
                    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
                    this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
                }
                else if (i > 0)
                {

                    this.notifyIcon1.Icon = global::BTVPodcatcherNamespace.Properties.Resources.Iconblue;
                }
                else if (i < 0)
                {
                    this.notifyIcon1.Icon = global::BTVPodcatcherNamespace.Properties.Resources.IconGreen;
                }
            }
            
        }
        

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        public string BTVServer
        {
            get
            {
                return _BTVServer;
            }
        }
        public string BTVPort
        {
            get { return _BTVPort; }
        }
        public string BTVUsername
        {
            get { return _BTVUsername; }
        }
        public string BTVPassword
        {
            get { return _BTVPassword; }
        }
        public int updateTimerAmount
        {
            get { return _updateTimerAmount; }
        }
        public int writeMediaInfoAfter
        {
            get { return _writeMediaAfter; }
        }
        public bool useTempFiles
        {
            get { return _useTEMPFiles; }
        }
        public int maxWriteAmount
        {
            get { return _maximumWriteAmount; }
        }
        public List<RSSLibrary3.RSSFeed> rssFeeds
        {
            get { return _rssFeeds; }
            set { _rssFeeds = value; }
        }
        public List<DowloadInfo> allDownloadingItems
        {
            get { return _allDownloadItems; }
            set { _allDownloadItems = value; }
        }
        public bool showWhenMinimzied
        {
            get { return _showWhenMinimized; }
        }
        

        

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void setupPrograToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProgramSetupForm psf = new ProgramSetupForm();
            psf.MdiParent = this;
            psf.loadSettings();
            psf.Show();
        }
        public void loadSettings(string BTVServer, string BTVPort, string BTVUsername, string BTVPassword, int updateAmount, int writeMedaAfter, int maxWriteAmount, bool useTmpFiles, bool showWhenMinimized, int throttleSpeed, TimeSpan start, TimeSpan stop, bool useSSL, bool readOnly, bool useUnsafeHTMLHandeling)
        {
            _BTVServer = BTVServer;
            _BTVPort = BTVPort;
            _BTVUsername = BTVUsername;
            _BTVPassword = BTVPassword;
            _updateTimerAmount = updateAmount;
            _useTEMPFiles = useTmpFiles;
            _writeMediaAfter = writeMedaAfter;
            _maximumWriteAmount = maxWriteAmount;
            _showWhenMinimized = showWhenMinimized;
            timer1.Interval = _updateTimerAmount * 60000;
            timer1.Stop();
            timer1.Start();
            _throttleAmount = throttleSpeed;
            _startTimeSpan = start;
            _stopTimeSpan = stop;
            _useSSL = useSSL;
            _readOnly = readOnly;
            _useUnsafeHTMLHeaderParsing =useUnsafeHTMLHandeling;
            if(_useUnsafeHTMLHeaderParsing)
            {
                SetAllowUnsafeHeaderParsing20();
            }else
            {
                SetDenyUnsafeHeaderParsing20();
            }

            writeSettingsFiles();
            toolStripStatusLabel.Text = "Program Settings Saved";
        }
        private void writeSettingsFiles()
        {
            System.IO.FileInfo fi =new System.IO.FileInfo(Environment.GetFolderPath( Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2\\BTVPodCatcherConfig2.xml");
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            
            //System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2");
            
            //System.IO.File.Create(fi.FullName);
            XmlTextWriter textWriter = new XmlTextWriter(fi.FullName, Encoding.Default);
            textWriter.WriteStartDocument();
            textWriter.WriteComment("BTVPodCatcher2ConfigFile");
            textWriter.WriteComment("File Written On "+DateTime.Now.ToString());
            textWriter.WriteStartElement("Config");
            textWriter.WriteStartElement("BTVServer");
            textWriter.WriteString(_BTVServer);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("BTVPort");
            textWriter.WriteString(_BTVPort);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("BTVUsername");
            textWriter.WriteString(_BTVUsername);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("BTVPass");
            textWriter.WriteString(EncDec.Encrypt(_BTVPassword,"oafjrivfkoQRQ(#:~WERmvi4,cdlsRFWREWFW$#o4mifo vmldssdoioegmwowE&#@F289-2r5t';;fgdvsT"));
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("Update");
            textWriter.WriteString(""+_updateTimerAmount);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("WriteMediaAfter");
            textWriter.WriteString("" + _writeMediaAfter);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("useTempFiles");
            textWriter.WriteString(useTempFiles.ToString());
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("maxWriteAmount");
            textWriter.WriteString(""+_maximumWriteAmount);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("showWhenMinimized");
            textWriter.WriteString("" + _showWhenMinimized);
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("useSSL");
            textWriter.WriteString("" + _useSSL.ToString());
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("startTime");
            textWriter.WriteString(_startTimeSpan.ToString());
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("endTime");
            textWriter.WriteString(_stopTimeSpan.ToString());
            textWriter.WriteEndElement();
            textWriter.WriteStartElement("throttleAmount");
            textWriter.WriteString(_throttleAmount.ToString());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("SetDownloadedFilesToReadOnly");
            textWriter.WriteString(_readOnly.ToString());
            textWriter.WriteEndElement();

            textWriter.WriteStartElement("useUnsafeHTMLHeaderParsing");
            textWriter.WriteString(_useUnsafeHTMLHeaderParsing.ToString());
            textWriter.WriteEndElement();

            textWriter.WriteEndElement();
            textWriter.WriteEndDocument();
            textWriter.Close();
            ConsoleForm.addMessage("Settings File Wrote");
        
        }

        private void loadSettingsFiles()
        {
            if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2\\BTVPodCatcherConfig2.xml"))
            {
                XmlTextReader textReader = new XmlTextReader(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2\\BTVPodCatcherConfig2.xml");

                XmlDocument xmlDoc = new XmlDocument(); ;
                XmlNode xmlNode = null;
                try
                {
                    xmlDoc.Load(textReader);
                    for (int i = 0; xmlDoc != null && i < xmlDoc.ChildNodes.Count; i++)
                    {
                        if (xmlDoc.ChildNodes[i].Name == "Config")
                        {
                            xmlNode = xmlDoc.ChildNodes[i];
                        }
                    }
                    if (xmlNode != null)
                    {
                        if (xmlNode["BTVServer"] != null)
                            _BTVServer = xmlNode["BTVServer"].InnerText;
                        if (xmlNode["BTVPort"] != null)
                            _BTVPort = xmlNode["BTVPort"].InnerText;
                        if (xmlNode["BTVUsername"] != null)
                            _BTVUsername = xmlNode["BTVUsername"].InnerText;
                        try
                        {
                            _BTVPassword = EncDec.Decrypt(xmlNode["BTVPass"].InnerText, "oafjrivfkoQRQ(#:~WERmvi4,cdlsRFWREWFW$#o4mifo vmldssdoioegmwowE&#@F289-2r5t';;fgdvsT");
                        }
                        catch (Exception)
                        {
                            ConsoleForm.addMessage("Error Decrpting Password");
                        }

                        if (int.TryParse(xmlNode["Update"].InnerText, out _updateTimerAmount))
                        {


                        }
                        else
                        {
                            _updateTimerAmount = 60;

                            ConsoleForm.addMessage("ERROR Occured update is not a number");
                        }
                        if (int.TryParse(xmlNode["WriteMediaAfter"].InnerText, out _writeMediaAfter))
                        {

                        }
                        else
                        {
                            ConsoleForm.addMessage("Error write media info after not a int");
                        }
                        if (int.TryParse(xmlNode["maxWriteAmount"].InnerText, out _maximumWriteAmount))
                        {

                        }
                        else
                        {
                            ConsoleForm.addMessage("Error Max was not an int");
                        }

                        if (xmlNode["useTempFiles"] != null && xmlNode["useTempFiles"].InnerText.ToLower().Equals("false"))
                            _useTEMPFiles = false;
                        else
                            _useTEMPFiles = true;
                        if (xmlNode["showWhenMinimized"] != null && xmlNode["showWhenMinimized"].InnerText.ToLower().Equals("false"))
                            _showWhenMinimized = false;
                        else
                            _showWhenMinimized = true;
                        if (xmlNode["throttleAmount"] != null)
                            _throttleAmount = Convert.ToInt32(xmlNode["throttleAmount"].InnerText);
                        if (xmlNode["startTime"] != null)
                            _startTimeSpan = Convert.ToDateTime(xmlNode["startTime"].InnerText).TimeOfDay;
                        if (xmlNode["endTime"] != null)
                            _stopTimeSpan = Convert.ToDateTime(xmlNode["endTime"].InnerText).TimeOfDay;
                        if (xmlNode["useSSL"] != null && xmlNode["useSSL"].InnerText.ToLower().Equals("true"))
                            _useSSL = true;
                        else
                            _useSSL = false;

                        if (xmlNode["SetDownloadedFilesToReadOnly"] != null && xmlNode["SetDownloadedFilesToReadOnly"].InnerText.ToLower().Equals("true"))
                            _readOnly = true;
                        else
                            _readOnly = false;

                        if (xmlNode["useUnsafeHTMLHeaderParsing"] != null && xmlNode["useUnsafeHTMLHeaderParsing"].InnerText.ToLower().Equals("true"))
                        {
                            _useUnsafeHTMLHeaderParsing = true;
                            SetAllowUnsafeHeaderParsing20();
                        }
                        else
                        {
                            _useUnsafeHTMLHeaderParsing = false;
                            SetDenyUnsafeHeaderParsing20();
                        }

                    }
                    ConsoleForm.addMessage("Settings File Loaded");
                }
                catch (XmlException xmlE)
                {
                    ConsoleForm.addMessage("Error With XML Format Of Settings File"+xmlE.ToString());
                }
                textReader.Close();
            }
            else
            {
                ConsoleForm.addMessage("Settings File Not Found");
            }

            timer1.Interval = _updateTimerAmount * 60000;
            writeSettingsFiles();
        }

        private void quickLaunchBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            toolStrip1.Visible = quickLaunchBarToolStripMenuItem.Checked;
        }

        private void feedSetupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FeedSetup fs = new FeedSetup();
            fs.MdiParent = this;
            fs.loadBTVFolders();
            fs.Show();
        }

        private void feedViewerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FeedViewer fv = new FeedViewer();
            fv.MdiParent = this;
            fv.setRSSItems();
            fv.Show();
        }

        public void writeBTVFeedFile()
        {
            try
            {

                System.IO.FileInfo fi = new System.IO.FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2\\FeedInfo2.bpc");
                if (!fi.Directory.Exists)
                {
                    fi.Directory.Create();
                }

                Stream stream = File.Open(fi.FullName, FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(stream, _rssFeeds);
                stream.Close();
                ConsoleForm.addMessage("Feed File Wrote");
            }
            catch (Exception e)
            {
                ConsoleForm.addMessage("Error Writing Feed File\r\n "+e.ToString());
            }
        
        }
        
        public void readBTVFeedFile()
        {
            Stream stream = null;
            try
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\BTVPodcatcher2\\FeedInfo2.bpc");
                if (fi.Exists)
                {
                    stream = File.Open(fi.FullName, FileMode.Open);
                    BinaryFormatter bformatter = new BinaryFormatter();
                    _rssFeeds = (List<RSSLibrary3.RSSFeed>)bformatter.Deserialize(stream);
                    ConsoleForm.addMessage("Feed File Loaded");
                }
                else
                {
                    ConsoleForm.addMessage("Feed File Does Not Exists");
                }
                //prssClass
                //prssClass.RSSItems[0].
                //stream.Close();
            }
            catch (Exception e)
            {
                ConsoleForm.addMessage("Error Loading FeedFile\r\n"+e.ToString());
                System.Console.WriteLine("Error opening FeedInfo2.bpc " + e.Message);

            }
            if (stream != null)
            {
                stream.Close();
            }

        }

        public void downloadRSSItems(List<RSSLibrary3.RSSItem> toDownload)
        {
            if(toDownload !=null)
            {
                foreach (RSSLibrary3.RSSItem ri in toDownload)
                {
                    downloadRSSItem(ri);
                }

            }
        }
        public void downloadRSSItem(RSSLibrary3.RSSItem downloadItem)
        {
            string filename = downloadItem.downloadURL.Trim();
            if(filename!=null&&filename.Length>0)
            {
                try
                {
                    if (filename.Contains("/"))
                    {
                        filename = filename.Substring(filename.LastIndexOf("/") + 1);
                    }
                    if (filename.Contains("?"))
                    {
                        filename = filename.Substring(0, filename.IndexOf("?"));
                    }
                    if (filename.ToLower().EndsWith(".divx") || filename.ToLower().EndsWith(".xvid"))
                    {
                        filename = filename.Substring(0, filename.Length - 5) + ".avi";
                    }
                    if (filename.EndsWith(".avi") || filename.EndsWith(".wmv") || filename.EndsWith(".mp4") || filename.EndsWith(".m4v") || filename.EndsWith(".tp") || filename.EndsWith(".mpeg") || filename.EndsWith(".mpg"))
                    {

                        FileInfo fi = new FileInfo(downloadItem.rssFeed.saveLocation + "\\" + filename);
                        string tmpFileName = fi.FullName;
                        int count = 0;
                        while (fi.Exists)
                        {
                            count++;
                            fi = new FileInfo(tmpFileName);
                            fi = new FileInfo(fi.FullName.Substring(0, fi.FullName.Length - fi.Extension.Length) + "-" + count + fi.Extension);

                        }
                        DowloadInfo di = new DowloadInfo(downloadItem.downloadURL, fi.FullName);
                        di.useTempFile = _useTEMPFiles;
                        di.RSSItem = downloadItem;
                        _allDownloadItems.Add(di);






                        if (downloadAdded != null)
                        {
                            downloadAdded(this, new DownloadInfoEventArgs(di));
                        }
                        int extraOne = DownloadManager.numberRunning;
                        if (DownloadManager.numberRunning < 2)
                        {
                            if (!backgroundWorker1.IsBusy)
                            {
                                setNotifyIcon(1);
                            }
                            _downloadManager.StartDownload(di, _throttleAmount);
                            extraOne++;
                        }
                        else
                        {
                            _toDownload.Enqueue(di);
                        }
                        setDownloadStatusLabel("Downloading " + (_toDownload.Count + extraOne) + " Items");
                        ConsoleForm.addMessage("Add Item To Download Manager");
                    }
                    else
                    {
                        ConsoleForm.addMessage("File is not a movie");
                    }
                }
                catch (Exception e)
                {
                    // MessageBox.Show("Error with filename or download URL "+downloadItem.downloadURL,"Error Trying to Download", MessageBoxButtons.OK,MessageBoxIcon.Error);
                    ConsoleForm.addMessage("Error with filename or download URL " + downloadItem.downloadURL + "\r\n" + e.ToString());
                }

            }else
                {
                   // MessageBox.Show("No File to Download","Error Trying to Download",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    ConsoleForm.addMessage("No File to Download");
                }
        }

        private void updateAllFeeds()
        {
            if (!backgroundWorker1.IsBusy)
            {
                toolStripStatusLabel.Text = "Updateing Feeds";

                toolStripProgressBar1.Visible = true;
                toolStripProgressBar1.Value = 0;
                ConsoleForm.addMessage("Update All Feeds");
                backgroundWorker1.RunWorkerAsync();
            }
        }
        
        private void timer1_Tick(object sender, EventArgs e)
        {
            if ((_startTimeSpan == _stopTimeSpan) || (_startTimeSpan < _stopTimeSpan && DateTime.Now.TimeOfDay > _startTimeSpan && DateTime.Now.TimeOfDay < _stopTimeSpan) || (_stopTimeSpan < _startTimeSpan && (DateTime.Now.TimeOfDay < _stopTimeSpan || DateTime.Now.TimeOfDay > _startTimeSpan)))
            {
                updateAllFeeds();
                ConsoleForm.addMessage("Timer Up");
            }
        }
        

        private void reloadFeedsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            updateAllFeeds();
        }

        private string currentFeed = "";
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            setNotifyIcon(-1);
            int i = 0;
            foreach (RSSLibrary3.RSSFeed rf in _rssFeeds)
            {
                
                currentFeed = rf.title;
                backgroundWorker1.ReportProgress((int)((i/(double)_rssFeeds.Count)*100));
                downloadRSSItems(rf.loadRssItems(true));

                if (rf.exception != null)
                {
                    ConsoleForm.addMessage("Feed Update Exception " + rf.exception);
                }
                i++;

            }
            writeBTVFeedFile();

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
            UpdateFeedStatusLabel();
            
        }
        private delegate void UpdateFeedStatusLabelDelegate();
        private void UpdateFeedStatusLabel()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new UpdateFeedStatusLabelDelegate(UpdateFeedStatusLabel));
            }
            else
            {
                try
                {
                    toolStripStatusLabel.Text = "Updating " + currentFeed;
                    notifyIcon1.Text = "BTV Podcatcher\r\nUpdating " + currentFeed;
                }
                catch (Exception)
                {

                }
            }
        }


        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                notifyIcon1.Text = "BTV Podcatcher";
                toolStripStatusLabel.Text = "Feeds Updated @ " + DateTime.Now.ToString();
                toolStripProgressBar1.Value = 0;
                setNotifyIcon(DownloadManager.numberRunning);
            }
            catch (Exception)
            {

            }
        }

        private void downloadManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DownloadViewer dv = new DownloadViewer();
            dv.MdiParent = this;
            dv.setupForm();
            dv.Show();
        }

        private void menuStrip_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
            {
                if (!_showWhenMinimized)
                {
                    Visible = false;
                    notifyIcon1.Visible = true;
                }
                else
                {
                    notifyIcon1.Visible = false;
                }
            }
            else
            {
                notifyIcon1.Visible = false;
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
           /* Visible = true;
            notifyIcon1.Visible = false;
            Focus();
            Select();
            */
            notifyIcon1.Visible = false;
            Show();
            BringToFront();
            this.Activate();
            WindowState = FormWindowState.Normal;
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            Show();
            BringToFront();
            this.Activate();
            WindowState = FormWindowState.Normal;
        }

        private void hideWindowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Visible = false;
            notifyIcon1.Visible = true;
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox1 a = new AboutBox1();
            a.Show(this);
        }

        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
            Help.ShowHelp(this, "BTVPodcatcher.chm");
            
        }

        private void indexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelpIndex(this, "BTVPodcatcher.chm");
            
        }

        private void cancelAllDownloadsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DowloadInfo di in _allDownloadItems)
                {
                    if (di.DownloadStatus == DownloadStatus.Downloading || di.DownloadStatus == DownloadStatus.Ready)
                    {
                        di.DownloadStatus = DownloadStatus.CancelRequested;
                        di.ADownloadChangedOccured(new EventArgs());
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void showConsoleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConsoleForm cf = new ConsoleForm();
            cf.MdiParent = this;
            cf.Show();
        }

        private void newDownloadManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NEWDownloadViewer ndv = new NEWDownloadViewer();
            ndv.MdiParent = this;
            ndv.setupForm();
            ndv.Show();
        }
        public delegate void DownloadAddedDelegate(object sender, DownloadInfoEventArgs e);
        public event DownloadAddedDelegate downloadAdded;
        public delegate void DownloadRemovedDelegate(object sender, EventArgs e);
        public event DownloadRemovedDelegate downloadRemovedEvent;


        public void downloadRemoved()
        {
            if (downloadRemovedEvent != null)
            {
                downloadRemovedEvent(this, new EventArgs());
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            NEWDownloadViewer ndv = new NEWDownloadViewer();
            ndv.MdiParent = this;
            ndv.setupForm();
            ndv.Show();
        }

        

        
       
    }
    public class DownloadInfoEventArgs : EventArgs
    {
        public DowloadInfo di;
        public DownloadInfoEventArgs(DowloadInfo _di)
        {
            di = _di;
        }
    } 
}
